<?php

namespace Admin\Controller;

use Think\Hook;

class ModelController extends AdminController
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function test()
    {
        $this->display();
    }

    public function index()
    {
        $this->IS_POST(function () {
            $model = D('Model');
            $d = M('Model')->create();
            $map = $d ?: array();
            $keyword = '%' . str_replace(' ', '%', I('keyword')) . '%';
            $like['name|title|engine_type'] = array('like', $keyword);
            $map['_complex'] = $like;
            $data = $model->where($map)->findPage();
            foreach ($data['data'] as &$row) {
                $row['create_time'] = date('Y-m-d H:i:s', $row['create_time']);
            }
            $this->ajaxReturn($data);
        });
        $this->_web('title', '模型管理');
        $this->_web('panel_title', '模型列表');
        $this->assign('searchTpl', 'searchModel');
        $listData = array(
            'url' => U(''),
            'toolbar' => '#barDemo',
            'toolbarTpl' => 'toolbar',
            'page' => true,
        );
        $listData['cols'][] = array('type' => 'checkbox', 'fixed' => 'left');
        $listData['cols'][] = array('field' => 'id', 'title' => 'ID', 'sort' => true);
        $listData['cols'][] = array('field' => 'name', 'title' => '模型标识', 'width' => '20%');
        $listData['cols'][] = array('field' => 'title', 'title' => '模型名称', 'width' => '25%');
        $listData['cols'][] = array('field' => 'create_time', 'title' => '创建时间', 'width' => '25%');
        $listData['cols'][] = array('fixed' => 'right', 'width' => '220', 'title' => '操作', 'toolbar' => '#rowBar');
        $this->displayList($listData);
    }

    /**
     * 数据列表
     * @param string $id
     */
    public function dataList($id = '')
    {
        $model = D('Model');
        $info = $model->find($id);
        if (!$info) {
            $this->error('找不到模型');
        }
        Hook::listen('MODEL_DATA_LIST_BEGIN', $info); // 模型数据开始
        $this->IS_POST(function () use ($model, $info) {
            $dao = M('\Common\Model\BaseModel:' . $info['name']);
            $map = $dao->create();
            $map = $map ?: array();
            if ($info['search_field'] && isset($_POST['keyword'])) {
                // 关键词搜索
                $search_field = explode(',', $info['search_field']);
                $keyword = '%' . str_replace(' ', '%', I('keyword')) . '%';
                $like = array();
                foreach ($search_field as $field) {
                    $like[$field] = array('like', $keyword);
                }
                $like['_logic'] = 'or';
                $map['_complex'] = $like;
            }
            $data = $dao->where($map)->findPage(I('limit') ? I('limit') : $info['list_grid']);
            $this->ajaxReturn($data);
        });
        $this->_web('title', '[' . $info['title'] . '] 数据列表');
        $this->_web('panel_title', '[' . $info['title'] . '] 数据列表');
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('fieldList'), 'title' => $this->get('_web')['panel_title']),
        ));
        $listData = array(
            'url' => U('', array('id' => $id)),
            'toolbar' => '#barDemo',
            'toolbarTpl' => 'data_tool',
            'page' => true,
        );
        $list_field = $model->parseListGrid($info['list_grid']);
        $listData['cols'] = $list_field;
        $info['search_field'] && $this->assign('searchTpl', 'dataSearch');
        $param = array(
            'info' => &$info,
            'listData' => &$listData,
            'assign' => function ($key, $val) {
                $this->assign($key, $val);
            },
        );
        Hook::listen('MODEL_DATA_LIST_END', $param); // 模型数据结束
        $this->assign('model_id', $id);
        $this->displayList($listData, $info['template_list']);
    }

    public function dataAdd()
    {
        $model_id = I('model_id');
        $id = I('id');
        $model = D('Model');
        $modelInfo = $model->find($model_id);
        $param = array('model_id' => &$model_id, 'id' => &$id);
        // 监听开始
        Hook::listen('MODEL_DATA_ADD_BEGIN', $param);
        if (!$modelInfo) $this->error('找不到模型');
        $modelInfo['model_field'] = D('Common/ModelField')->getFormFields($model_id);
        $dao = M('\Common\Model\BaseModel:' . $modelInfo['name']);
        $this->IS_POST(function () use ($dao, $modelInfo) {
            $this->saveData($dao, $modelInfo, I('post.'));
            exit;
        });
        $this->_web('title', '添加数据');
        $this->_web('panel_title', '添加数据');
        // 面包屑导航
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('dataList', array('id' => $model_id)), 'title' => '数据管理'),
            array('url' => U('fieldList'), 'title' => $this->get('_web')['panel_title']),
        ));
        // 监听结束
        Hook::listen('MODEL_DATA_ADD_END', $modelInfo);
        $this->assign('modelInfo', $modelInfo);
        $this->assign('model_id', $model_id);
        $this->display($modelInfo['template_add'] ?: 'dataEdit');
    }

    public function dataEdit()
    {
        $model_id = I('model_id');
        $id = I('id');
        $model = D('Model');
        $modelInfo = $model->find($model_id);
        $param = array('model_id' => &$model_id, 'id' => &$id);
        // 监听开始
        Hook::listen('MODEL_DATA_EDIT_BEGIN', $param);
        if (!$modelInfo) $this->error('找不到模型');
        $modelInfo['model_field'] = D('Common/ModelField')->getFormFields($model_id);
        $dao = M('\Common\Model\BaseModel:' . $modelInfo['name']);
        $info = $dao->find($id);
        if (!$info) $this->error('找不到数据');
        $this->IS_POST(function () use ($dao, $modelInfo) {
            $this->saveData($dao, $modelInfo, I('post.'));
            exit;
        });
        $this->_web('title', '编辑数据');
        $this->_web('panel_title', '编辑数据');
        // 面包屑导航
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('dataList', array('id' => $model_id)), 'title' => '数据管理'),
            array('url' => U('fieldList'), 'title' => $this->get('_web')['panel_title']),
        ));
        $param = array('modelInfo' => &$modelInfo, 'info' => &$info);
        // 监听结束
        Hook::listen('MODEL_DATA_EDIT_END', $param);
        $this->assign('info', $info);
        $this->assign('modelInfo', $modelInfo);
        $this->assign('model_id', $model_id);
        $this->display($modelInfo['template_edit'] ?: 'dataEdit');
    }

    /**
     * 数据保存
     * @param $dao
     * @param $info
     * @param $data
     */
    protected function saveData($dao, $info, $data)
    {
        $validate_rules = D('ModelField')->getFieldsValidateRules($info['model_field']); // 获取字段自动验证规则
        $auto_rules = D('ModelField')->getFieldsAutoRules($info['model_field']); // 获取字段自动完成规则
        if ($validate_rules) $dao = $dao->validate($validate_rules); // 保存连贯
        if ($auto_rules) $dao = $dao->auto($auto_rules); // 保存连贯
        $d = $dao->create($data);
        if (!$d) $this->error($dao->getError());
        if ($d['id']) {
            $res = $dao->save($d) !== false ? true : false;
        } else {
            $res = $dao->add($d);
            $url = U('dataList',['id'=>$info['id']]);
        }
        if ($res)
            $this->success('操作成功', $url);
        else
            $this->error('操作失败');
    }

    /**
     * 删除模型数据
     */
    public function delData()
    {
        $model_id = I('model_id');
        $model_name = D('Model')->getFieldById($model_id, 'name');
        Hook::listen('MODEL_DATA_DEL_BEGIN', $model_id);
        if (!$model_name) {
            $this->error('找不到模型');
        }
        $model = M('\Common\Model\BaseModel:' . $model_name);
        $ids = I('request.ids') ?: I('request.id');
        if (empty($ids)) {
            $this->error('请选择要操作的数据');
        }
        $url = '';
        if ($ids) {
            $map = array('id' => array('in', $ids));
            $res = $model->where($map)->delete();
            $param = array(
                'result' => &$res,
                'ids' => &$ids,
                'model_name' => &$model_name,
                'back_url' => &$url,
            );
            Hook::listen('MODEL_DATA_DEL_END', $param);
            if ($res) {
                $this->success('删除成功', $url);
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 字段列表
     * @param string $id
     */
    public function fieldList($id = '')
    {
        $this->IS_POST(function () use ($id) {
            $model = D('ModelField');
            $d = M('ModelField')->create();
            $map = $d ?: array();
            $map['model_id'] = $id;
            $keyword = '%' . str_replace(' ', '%', I('keyword')) . '%';
            $like['name|title|attribute|remark|error_info'] = array('like', $keyword);
            $map['_complex'] = $like;
            $data = $model->where($map)->findPage();
            $field_type = $model->parseFieldType();
            foreach ($data['data'] as &$row) {
                $row['form'] = $field_type[$row['form']][0];
                $row['create_time'] = date('Y-m-d H:i:s', $row['create_time']);
            }
            $this->ajaxReturn($data);
        });
        $this->_web('title', '模型字段');
        $this->_web('panel_title', '模型字段');
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('fieldList'), 'title' => $this->get('_web')['panel_title']),
        ));
        $this->assign('model_id', $id);
        $this->assign('searchTpl', 'searchModel');
        $listData = array(
            'url' => U('', array('id' => $id)),
            'toolbar' => '#barDemo',
            'toolbarTpl' => 'field_tool',
            'page' => true,
        );
        $listData['cols'][] = array('type' => 'checkbox', 'fixed' => 'left');
        $listData['cols'][] = array('field' => 'id', 'title' => 'ID', 'sort' => true);
        $listData['cols'][] = array('field' => 'name', 'title' => '字段标识', 'width' => '15%');
        $listData['cols'][] = array('field' => 'title', 'title' => '字段名称', 'width' => '20%');
        $listData['cols'][] = array('field' => 'form', 'title' => '字段类型', 'width' => '10%');
        $listData['cols'][] = array('field' => 'create_time', 'title' => '创建时间', 'width' => '25%');
        $listData['cols'][] = array('fixed' => 'right', 'width' => '220', 'title' => '操作', 'toolbar' => '#rowBar');
        $this->displayList($listData);
    }

    /**
     * 添加字段
     * @param string $model_id
     * @param string $id
     */
    public function addField($model_id = '', $id = '')
    {
        $model = D('ModelField');
        if (!$model_id) {
            $this->error('没有指定模型');
        } else if (!M('Model')->where(array('id' => $model_id))->count()) {
            $this->error('模型不存在');
        }
        $this->IS_POST(function () use ($model, $id, $model_id) {
            $data = $model->create();
            $m = array(
                'id' => $id,
                'model_id' => $model_id
            );
            if (!$data) {
                $this->error($model->getError());
            } else if ($model->in2replace($data, $m) !== false) {
                $this->success('操作成功', U('fieldList', array('id' => $model_id)));
            }
            $this->error('操作失败');
        });
        $this->_web('title', '添加字段');
        $this->_web('panel_title', '添加字段');
        if ($id) {
            $info = $model->find($id);
            $this->assign('info', $info);
            $this->_web('title', '编辑字段');
            $this->_web('panel_title', '编辑字段');
        }
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('fieldList', array('id' => $model_id)), 'title' => '字段列表'),
            array('url' => U('addField', array('model_id' => $model_id)), 'title' => $this->get('_web')['panel_title']),
        ));
        $fieldType = array();
        $parseType = $model->parseFieldType();
        $validate_type = C('FIELD_VALIDATE_TYPE');
        foreach ($parseType as $key => $row) {
            $fieldType[$key] = $row[0];
        }
        $this->assign('model_id', $model_id);
        $this->assign('field_type', $fieldType);
        $this->assign('validate_type', $validate_type);
        $this->assign('parse_field_type', $parseType);
        $this->display();
    }

    /**
     * 添加模型
     * @param string $id
     */
    public function add($id = '')
    {
        $model = D('Model');
        $this->_web('title', '添加模型');
        $this->_web('panel_title', '添加模型');
        if ($id) {
            $info = $model->find($id);
            if (!$info) $this->error('找不到模型');
            $this->_web('title', '编辑模型');
            $this->_web('panel_title', '编辑模型');
        }
        $this->IS_POST(function () use ($model, $id) {
            $data = $model->create();
            if (!$data) {
                $this->error($model->getError());
            } else if ($model->in2replace($data, array('id' => $id)) !== false) {
                $this->success('操作成功', U('index'));
            }
            $this->error('操作失败');
        });
        $this->_web('breadcrumb', array(
            array('url' => U('index'), 'title' => '模型管理'),
            array('url' => U('add'), 'title' => $this->get('_web')['panel_title']),
        ));
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 删除字段
     */
    public function delField()
    {
        $this->model = D('ModelField');
        $this->del();
    }

    /**
     * 模型删除 前置
     */
    public function _before_del()
    {
        $this->model = D('Model');
    }

    public function _beging_del($ids, &$url)
    {
        $url = false;
    }
}